package br.com.massai.model.business;

import java.util.List;
import java.util.Random;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import br.com.massai.model.dao.CollaboratorRepository;
import br.com.massai.model.entity.Collaborator;
import br.com.massai.model.exceptions.ErrorCore;
import br.com.massai.model.exceptions.SystemException;

@Stateless
public class CollaboratorFacade implements CollaboratorBusiness {

	private static final long serialVersionUID = -8321317515675098134L;

	@EJB private CollaboratorRepository collaboratorRepository;

	@Override
	public Collaborator findID(Long id) throws SystemException {
		return collaboratorRepository.findID(id);
	}

	@Override
	public Collaborator save(Collaborator entity) throws SystemException {
		checkBusinessRule(entity);
		if(entity.getId() == null) return collaboratorRepository.create(entity);
		else return collaboratorRepository.update(entity);
	}
	
	@Override
	public void delete(Collaborator entity) throws SystemException {
		collaboratorRepository.delete(entity);
	}

	@Override
	public void checkBusinessRule(Collaborator entity) throws SystemException {
		if(entity == null) throw new SystemException(ErrorCore.ERROR_ILLEGAL_ARGUMENT);
		if(entity.getUsername() == null || entity.getUsername().isEmpty()) throw new SystemException(ErrorCore.ERROR_REQUIRED_FIELD, "Login");
		if(entity.getPassword() == null || entity.getPassword().isEmpty()) throw new SystemException(ErrorCore.ERROR_REQUIRED_FIELD, "Senha");
		if(entity.getEmail() == null || entity.getEmail().isEmpty()) throw new SystemException(ErrorCore.ERROR_REQUIRED_FIELD, "Email");
		if(entity.getNameCollaborator() == null || entity.getNameCollaborator().isEmpty()) throw new SystemException(ErrorCore.ERROR_REQUIRED_FIELD, "Nome");
	}

	@Override
	public String resetPassword(Collaborator user) throws SystemException {
		try{
			if(user != null){
				String pass = generateRandomPassword();
				user.setPassword(pass);
				collaboratorRepository.update(user);
				return pass;

			} else {
				throw new Exception();
			}
		} catch (Exception e) {
			throw new SystemException(ErrorCore.ERROR_RESET_PASSWORD, e);
		}
	}

	@Override
	public List<Collaborator> getCollaboratorsActive() throws SystemException {
		return collaboratorRepository.getCollaboratorsActive();
	}

	@Override
	public Collaborator login(Collaborator collaborator) throws SystemException {
		return collaboratorRepository.login(collaborator);
	}

	@Override
	public String generateRandomPassword() throws SystemException {
		String words = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
		Random ran = new Random();
		String pword = "";
		int index = -1;
		for(int i = 0; i < 6; i++){
			index = ran.nextInt(words.length());
			pword += words.substring(index, index+1);
		}

		System.out.println("############# "+pword);
		return pword;
	}
}